import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_utils/screen.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/event_bus/events.dart';
import 'package:video_player/video_player.dart';

import '../../../hj_utils/date_time_util.dart';
import '../../../hj_utils/free_play_count_manager.dart';
import '../../../hj_utils/global.dart';
import '../../../hj_utils/player_util.dart';
import '../../../tools_base/event_bus/event_bus_util.dart';
import '../../short_video/view/short_progress_widget.dart';
import 'detail_top_right_view.dart';

class VideoMenuView extends StatefulWidget {
  final VideoPlayerController controller;
  final bool isFull;
  final Function? callback;
  final VideoModel? videoModel;
  final bool isFromPK; //免费视频 / pk 打榜视频,不显示免费次数
  final Function? onBuyEvent;

  const VideoMenuView(
      {super.key, required this.controller, this.isFull = false, this.callback, this.videoModel, this.isFromPK = false, this.onBuyEvent});

  @override
  State<StatefulWidget> createState() {
    return _VideoMenuViewState();
  }
}

class _VideoMenuViewState extends State<VideoMenuView> {
  VideoPlayerController get controller => widget.controller;
  Timer? _timer;
  Timer? _skipTimer;
  bool _showMenu = true;

  bool isPlaying = true;

  Duration? seekPos;
  bool _controllerWasPlaying = false;
  bool showSeekText = false;
  List<int> skipTimeArr = [];
  int skipForward = 0; // 1快进， -1 快退
  bool _showPlaySpeed = false;
  bool isLongPress = false; // 长按
  VideoPlayerController? preController;

  LongVideStatus get videoStatus => longVideoStatusDesc(widget.videoModel);

  double get curSpeed => controller.value.playbackSpeed;

  List<double> get speedArr => [0.5, 1.0, 1.5, 2.0];

  List<String> get speedDescArr => ["0.5", "1.0", "1.5", "2"];

  late StreamSubscription subscription;

  @override
  void initState() {
    super.initState();
    controller.addListener(listerCallback);
    subscription = eventBus.on<LongVideoMenuEvent>((_) {
      touchBeginEvent(isFromExternal: true);
    });
    startTimer();
  }

  void seekToAbsolutePosition(Offset delta) {
    if (seekPos == null || controller.value.isInitialized != true) return;
    int milliseconds = seekPos!.inMilliseconds + (800 * delta.dx).toInt();
    if (milliseconds < 0) {
      milliseconds = 0;
    } else if (milliseconds > controller.value.duration.inMilliseconds) {
      milliseconds = controller.value.duration.inMilliseconds;
    }
    seekPos = Duration(milliseconds: milliseconds);
    seekToPreVC();
    if (mounted) setState(() {});
  }

  bool isSeekPreVC = false;

  void seekToPreVC({Duration? seekDuration}) async {
    Duration? duration = seekDuration ?? seekPos;
    if (duration != null && preController?.value.isInitialized == true) {
      if (isSeekPreVC == true || preController?.value.position.inSeconds == duration.inSeconds) {
        return;
      }
      isSeekPreVC = true;
      try {
        debugLog("skipTO:${DateTimeUtil.formatDuration(duration)}");
        await preController?.seekTo(duration);
      } catch (e) {
        debugLog(e);
      }
      isSeekPreVC = false;
      setState(() {});
      if (seekPos != null && seekPos?.inSeconds != duration.inSeconds) {
        seekToPreVC(seekDuration: seekPos);
      }
    }
  }

  void doubleTapEvent(TapDownDetails details) {
    if (details.globalPosition.dx > screen.screenWidth / 2 + screen.screenWidth / 2 / 3) {
      _skipForward();
    } else if (details.globalPosition.dx < screen.screenWidth / 2 * 2 / 3) {
      _skipBack();
    }
  }

  void startTimer({bool isSkipTime = false}) {
    _timer?.cancel();
    _showMenu = true;
    setState(() {});
    if (isSkipTime == true && _skipTimer == null) {
      _skipTimer = Timer(const Duration(seconds: 1), () {
        skipForward = 0;
        if (mounted) {
          setState(() {});
        }
        _skipTimer?.cancel();
        _skipTimer = null;
      });
    }
    _timer = Timer(const Duration(seconds: 3), () {
      _showMenu = false;
      _showPlaySpeed = false;
      skipForward = 0;
      if (mounted) {
        setState(() {});
      }
      _timer?.cancel();
    });
  }

  void _playEvent(bool play) {
    isPlaying = play;
    setState(() {});
    if (play) {
      controller.play();
    } else {
      controller.pause();
    }
  }

  void listerCallback() {
    if (mounted) {
      setState(() {});
    }
  }

  void _skipBack() {
    skipForward = -1;
    startTimer(isSkipTime: true);
    final skip = (controller.value.position - const Duration(seconds: 10)).inMilliseconds;
    controller.seekTo(Duration(milliseconds: max(skip, 0)));
  }

  void _skipForward() {
    skipForward = 1;
    startTimer(isSkipTime: true);
    final end = controller.value.duration.inMilliseconds;
    final skip = (controller.value.position + const Duration(seconds: 10)).inMilliseconds;
    controller.seekTo(Duration(milliseconds: min(skip, end)));
  }

  bool isCanPlayPreviewVideo() {
    if (FreePlayCountManager().canFreePlay(widget.videoModel)) {
      return false;
    }
    if (widget.videoModel?.previewURL?.isNotEmpty == true && (needBuyVip(widget.videoModel) || needBuyVideo(widget.videoModel))) {
      return true;
    } else {
      return false;
    }
  }

  void touchBeginEvent({bool isFromExternal = false}) {
    //isFromExternal true:播放器页面外触发菜单显示
    if (_showMenu && !isFromExternal) {
      if (_showPlaySpeed == true) {
        startTimer();
        _showPlaySpeed = false;
        setState(() {});
        return;
      }
      _showMenu = false;
      _timer?.cancel();
      setState(() {});
      if (controller.value.isPlaying == true) {
        //_playEvent(false);
      } else {
        //_playEvent(true);
      }
    } else {
      isPlaying = controller.value.isPlaying == true;
      startTimer();
      // _playEvent(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: touchBeginEvent,
      onHorizontalDragStart: (DragStartDetails details) {
        if (controller.value.isInitialized != true) {
          return;
        }
        _controllerWasPlaying = controller.value.isPlaying;
        if (_controllerWasPlaying) {
          controller.pause();
        }
        seekPos = controller.value.position;
        showSeekText = true;
        setState(() {});
      },
      onHorizontalDragUpdate: (DragUpdateDetails details) {
        if (controller.value.isInitialized != true) {
          return;
        }
        startTimer();
        seekToAbsolutePosition(details.delta);
      },
      onHorizontalDragEnd: (DragEndDetails details) async {
        if (seekPos != null) {
          await controller.seekTo(seekPos!);
        }
        seekPos = null;
        if (_controllerWasPlaying) {
          controller.play();
        }
        showSeekText = false;
        setState(() {});
        startTimer();
      },
      onHorizontalDragCancel: () {
        showSeekText = false;
        setState(() {});
      },
      onDoubleTapDown: (detail) {
        _showPlaySpeed = false;
        doubleTapEvent(detail);
      },
      onLongPressUp: () {
        startTimer();
        isLongPress = false;
        controller.setPlaybackSpeed(1.0);
      },
      onLongPressEnd: (value) {
        startTimer();
        isLongPress = false;
        controller.setPlaybackSpeed(1.0);
      },
      onLongPressStart: (detail) {
        showToast("长按不动,2X倍速播放", gravity: ToastGravity.TOP);
        isLongPress = true;
        _showPlaySpeed = false;
        showSeekText = false;
        setState(() {});
        startTimer();
        controller.setPlaybackSpeed(2.0);
      },
      child: Visibility(
        visible: _showMenu || controller.value.isInitialized == false || isLongPress,
        child: Stack(
          fit: StackFit.expand,
          alignment: Alignment.center,
          children: [
            if (!widget.isFromPK)
              Positioned(
                bottom: 54,
                right: 0,
                child: VideoStatusView(
                  controller: widget.controller,
                  model: widget.videoModel,
                  onBuyEvent: widget.onBuyEvent,
                ),
              ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: _buildBottomMenu(),
            ),
            if (controller.value.isInitialized != true || controller.value.isBuffering == true)
              SizedBox() //_buildLoading()
            else if (!isPlaying)
              _buildPlayIcon()
            else
              const SizedBox(),
            if (showSeekText) _buildSeekText(),
            if (_showPlaySpeed)
              Positioned(
                right: 0,
                top: 0,
                bottom: 0,
                child: _buildPlaySpeed(),
              ),
            if (skipForward != 0)
              Positioned(
                left: (skipForward == 1) ? null : 0,
                right: (skipForward == 1) ? 0 : null,
                child: Container(
                  color: Colors.black.withOpacity(0.5),
                  padding: EdgeInsets.fromLTRB((skipForward == 1) ? 12 : 24, 12, (skipForward == 1) ? 24 : 12, 12),
                  child: Text(
                    skipForward == 1 ? "快进10秒 >>" : "<< 快退10秒",
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.8),
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildPlaySpeed() {
    return GestureDetector(
      onHorizontalDragStart: (detail) {},
      onHorizontalDragUpdate: (details) {},
      onHorizontalDragDown: (detail) {},
      onHorizontalDragCancel: () {},
      onHorizontalDragEnd: (detail) {},
      child: Container(
        width: 150,
        color: Color(0xff1E1F1E),
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: widget.isFull == true ? MainAxisAlignment.center : MainAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.only(left: 12),
              child: Row(
                children: [
                  Image.asset(
                    'arrow_down.png'.commonImgPath,
                    width: 14,
                    height: 14,
                  ),
                  6.sizeBoxW,
                  Text(
                    "播放速度",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 8),
            if (widget.isFull == true)
              ListView.builder(
                itemCount: speedArr.length,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: EdgeInsets.zero,
                itemBuilder: (context, index) {
                  bool isSelected = curSpeed == speedArr[index];
                  return _buildSpeedItem(index, isSelected);
                },
              )
            else
              Expanded(
                child: ListView.builder(
                  padding: EdgeInsets.zero,
                  itemCount: speedArr.length,
                  itemBuilder: (context, index) {
                    bool isSelected = curSpeed == speedArr[index];
                    return _buildSpeedItem(index, isSelected);
                  },
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSpeedItem(int index, bool isSelected) {
    return InkWell(
      onTap: () {
        if (!isSelected) {
          controller.setPlaybackSpeed(speedArr[index]);
        }
        _showPlaySpeed = false;
        setState(() {});
      },
      child: Container(
        height: 32,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 18),
        margin: const EdgeInsets.only(bottom: 8),
        decoration: BoxDecoration(
            border: Border(
          top: BorderSide(
            color: Color(0xff6A6765),
          ),
        )),
        child: Row(
          children: [
            if (isSelected)
              Icon(
                Icons.check,
                size: 14,
                color: Colors.white,
              )
            else
              SizedBox(width: 14),
            6.sizeBoxW,
            Text(
              "${speedDescArr[index]}倍",
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildBottomMenu() {
    return Container(
      height: 32,
      color: const Color(0xff04040a).withOpacity(0.4),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (controller.value.isInitialized) {
                if (controller.value.isPlaying) {
                  _playEvent(false);
                } else {
                  _playEvent(true);
                }
                startTimer();
              }
            },
            child: Container(
              height: 32,
              width: 36,
              padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
              alignment: Alignment.center,
              child: Image.asset(
                (isPlaying || controller.value.isPlaying == true) ? "pause_icon.webp".videoPath : "play.webp".videoPath,
                width: 24.w,
              ),
            ),
          ),
          Expanded(
            child: ShortProgressWidget(
              padding: EdgeInsets.zero,
              controller: controller,
              isShortStyle: false,
              skipCallback: (duration) {
                seekPos = duration;
                showSeekText = true;
                startTimer();
                seekToPreVC(seekDuration: duration);
              },
              gestureCallback: (value) {
                if (value) {
                  _timer?.cancel();
                } else {
                  showSeekText = false;
                  startTimer();
                }
              },
            ),
          ),
          InkWell(
            onTap: () {
              _showPlaySpeed = !_showPlaySpeed;
              startTimer();
            },
            child: Container(
                padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
                child: const Text(
                  "倍速",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                )),
          ),
          InkWell(
            onTap: () {
              widget.callback?.call();
            },
            child: Container(
              height: 26,
              width: 26,
              margin: const EdgeInsets.only(right: 6),
              child: Image.asset(
                "full_icon.png".videoPath,
                width: 26,
                height: 26,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlayIcon() {
    return Center(
      child: GestureDetector(
        behavior: HitTestBehavior.deferToChild,
        onTap: () {
          startTimer();
          _playEvent(true);
        },
        child: Image.asset(
          "play.webp".videoPath,
          width: 40,
          height: 40,
        ),
      ),
    );
  }

  Widget _buildSeekText() {
    Duration showDuration;
    if (seekPos != null) {
      showDuration = seekPos!;
    } else {
      showDuration = controller.value.position;
    }
    return Container(
      padding: const EdgeInsets.only(bottom: 8),
      alignment: Alignment.center,
      child: Column(
        children: [
          SizedBox(height: widget.isFull == true ? 24 : 12),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                DateTimeUtil.formatDuration(showDuration) ?? "",
                style: const TextStyle(
                  color: Color(0xff396af4),
                  fontSize: 18,
                ),
              ),
              if (controller.value.isInitialized == true)
                Text(
                  " /${DateTimeUtil.formatDuration(controller.value.duration)}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
            ],
          ),
          if (preController?.value.isInitialized == true)
            Container(
              width: 108 * 16 / 9,
              height: 108,
              margin: const EdgeInsets.only(top: 12),
              alignment: Alignment.center,
              color: Colors.black,
              child: AspectRatio(
                aspectRatio: preController!.value.aspectRatio,
                child: VideoPlayer(preController!),
              ),
            ),
        ],
      ),
    );
  }

  // GestureDetector _buildSkipBack() {
  //   return GestureDetector(
  //     onTap: _skipBack,
  //     child: Container(
  //       height: 40,
  //       color: Colors.transparent,
  //       margin: const EdgeInsets.only(left: 10.0),
  //       padding: const EdgeInsets.only(
  //         left: 6.0,
  //         right: 6.0,
  //       ),
  //       child: const Icon(
  //         CupertinoIcons.gobackward_15,
  //         color: Colors.white,
  //         size: 38.0,
  //       ),
  //     ),
  //   );
  // }
  //
  // GestureDetector _buildSkipForward() {
  //   return GestureDetector(
  //     onTap: _skipForward,
  //     child: Container(
  //       height: 40,
  //       color: Colors.transparent,
  //       padding: const EdgeInsets.only(
  //         left: 6.0,
  //         right: 8.0,
  //       ),
  //       margin: const EdgeInsets.only(
  //         right: 8.0,
  //       ),
  //       child: const Icon(
  //         CupertinoIcons.goforward_15,
  //         color: Colors.white,
  //         size: 38.0,
  //       ),
  //     ),
  //   );
  // }

  @override
  void dispose() {
    _timer?.cancel();
    _skipTimer?.cancel();
    controller.removeListener(listerCallback);
    preController?.dispose();
    subscription.cancel();
    super.dispose();
  }
}
